package com.eregg.learn.netty.demo.stickpack.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

public class FirstClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接成功，准备发送1000条消息");
        for (int i = 0; i < 1000; i++) {
            ByteBuf byteBuf = getByteBuf(i, ctx);
            ctx.channel().writeAndFlush(byteBuf);
            //Thread.sleep(1);
        }
        System.out.println("1000条消息发送完成");
    }

    private ByteBuf getByteBuf(int i, ChannelHandlerContext ctx) {
        ByteBuf byteBuf = ctx.alloc().buffer();
        byteBuf.writeBytes(String.format("%s:怒发冲冠，凭栏处、潇潇雨歇。抬望眼，仰天长啸，壮怀激烈。三十功名尘与土，八千里路云和月。", i).getBytes(Charset.forName("utf-8")));
        return byteBuf;
    }


}
